package com.chen.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chen.config.AliPayConfig;
import com.chen.entity.Order;
import com.chen.mapper.OrderMapper;
import com.chen.service.OrderPayService;
import com.chen.service.UserRechargeOrdersService;
import com.chen.utils.RedisWorker;
import com.chen.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;

/**
 * @author cws
 * @since
 */
@Service
@Slf4j
public class OrderPayServiceImpl implements OrderPayService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private RedisWorker redisWorker;

    @Resource
    AliPayConfig aliPayConfig;

    @Override
    public Result orderPay(String orderSn,String token) {
        Order order = orderMapper.selectOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderSn, orderSn));
        if (Objects.isNull(order)) {
            throw new RuntimeException("订单不存在");
        }
        if (!order.getStatus().equals(0)) {
            throw new RuntimeException("订单状态异常");
        }
        AlipayClient alipayClient = new DefaultAlipayClient(aliPayConfig.getGatewayUrl(), aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), aliPayConfig.getFormat(), aliPayConfig.getCharset(),
                aliPayConfig.getAlipayPublicKey(), aliPayConfig.getSignType());
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        log.info("=========支付宝统一收单交易创建接口========{}", aliPayConfig.getNotifyUrl());
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", order.getOrderSn());
        bizContent.put("total_amount", order.getPayAmount());
        HashMap<String, Object> map = new HashMap<>();
        map.put("orderSn", order.getOrderSn());
        map.put("type", "order");
        map.put("token",token);
        bizContent.put("subject", JSONUtil.toJsonStr(map));
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toString());
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(form);
    }

}

